//封装购物车模块
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { useUserStore } from './userStore'
import { insertCartAPI, findNewCartListAPI, delCartAPI } from '@/apis/cart'

export const useCartStore = defineStore('cart' , ()=>{
  const userStore = useUserStore()
  const isLogin = computed(()=>userStore.userInfo.token)

    //获取最新购物车列表action
  const updateNewList = async ()=>{
      const res =  await findNewCartListAPI()
      cartList.value = res.result
  }


  // 1.定义state-cartList
  const cartList = ref([])

  //2.定义action-addCart
  const addCart = async (goods) =>{
    const {skuId,count} = goods
    if(isLogin.value){
      //登录之后的购物车操作
      await insertCartAPI({skuId,count})
      updateNewList()
    }else{
      //未登录的购物车操作
      //添加购物车操作
    //已添加过则 count+1
    //没添加过则 直接push
    //思路： 通过匹配传递过来的商品对象中的skuId能不能在cartList中找到，找到了就是添加过了
    const item = cartList.value.find((item)=>goods.skuId === item.skuId)
    if(item){
      item.count++
    }else{
      cartList.value.push(goods)
    }
    }

  }

  //删除购物车商品
  const delCart = async (skuId)=>{
    if(isLogin.value){
      //调用接口实现删除
      await delCartAPI([skuId])
      updateNewList()
    }else{
    //思路：找到要删除项的下标值 - splice
    //或者使用数组的过滤方法 - filter
    const idx = cartList.value.findIndex((item)=>skuId === item.skuId)
    cartList.value.splice(idx,1)
    }


  }

  //清空购物车
  const clearCart = ()=>{
    cartList.value = []
  }

  //计算属性
  //1.总的数量 所有项的count之和
  const allCount =  computed(()=>cartList.value.reduce((a,c)=>a+c.count, 0))
  //2.总的价格 所有项的count*price之和
  const allPrice =  computed(()=>cartList.value.reduce((a,c)=>a+c.count*c.price, 0))
  //3.选中的商品数量
  const selectedCount = computed(()=>cartList.value.filter((item)=>item.selected).reduce((a,c)=>a+c.count, 0))
  //4.已选择的商品价钱合计
  const selectedPrice = computed(()=>cartList.value.filter((item)=>item.selected).reduce((a,c)=>a+c.count*c.price, 0))

  //单选功能
  const singleCheck = (skuId,selected)=>{
    //根据skuId找到要修改的那一项，然后把它的selected修改为传过来的selected
    const item = cartList.value.find((item)=>item.skuId === skuId)
    item.selected = selected
  }

  //全选功能
  const isAll = computed(()=> cartList.value.every((item)=>item.selected))
  //全选功能
  const allCheck = (selected)=>{
    //把cartList中的每一项的selected都设置为当前的全选框状态
    cartList.value.forEach((item)=>item.selected = selected)
  }


  //待结算商品
  const pendingGoods = ref([])

  //设置待结算商品（购物车点击“结算”时调用）
  const setPendingGoods = (goods)=>{
    pendingGoods.value = goods;
  }
  //清空待结算商品
  const clearPendingGoods = ()=>{
    pendingGoods.value = []
  }

  return{
    cartList,
    addCart,
    delCart,
    allCount,
    allPrice,
    selectedCount,
    selectedPrice,
    singleCheck,
    isAll,
    allCheck,
    clearCart,
    updateNewList,
    pendingGoods,
    setPendingGoods,
    clearPendingGoods
  }
},{
  persist:true,
  // 开启数据持久化
})
